﻿using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Newtonsoft.Json;
using UnityTemplate.ApiModel;

namespace UnityTemplate.API.Filter
{
    internal class ValidationFailedModel : BaseResponse
    {
        public ValidationFailedModel(ModelStateDictionary modelState)
        {
            Errors = modelState.Keys
                        .SelectMany(key => modelState[key].Errors.Select(x => new ValidationError(key, x.ErrorMessage)))
                        .ToList();
            Status = ApiStatus.FieldError;
            Title = "One or more validation errors occurred.";
        }
    }

    internal class ValidationError
    {
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string Field { get; }
        public string Message { get; }
        public ValidationError(string field, string message)
        {
            Field = field;
            Message = message;
        }
    }

    internal class ValidationFailedResult : ObjectResult
    {
        public ValidationFailedResult(ModelStateDictionary modelState)
         : base(new ValidationFailedModel(modelState))
        {
            StatusCode = ApiStatus.FieldError;
        }
    }

    public class ValidateModelAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                context.Result = new ValidationFailedResult(context.ModelState);
            }
        }

    }
}
